from rest_framework.views import exception_handler
from rest_framework import serializers
from rest_framework.exceptions import AuthenticationFailed
from jwt.exceptions import ExpiredSignatureError
from django.utils.datastructures import MultiValueDictKeyError
from .exception import CustomError
from utils import response_error

import traceback
import json


def custom_exception_handler(exc, context):
    message = ''
    errcode = None
    if isinstance(exc, CustomError):  # raise CustomError('xxxxxxxxxxx')
        message = exc.get_error_msg()
    elif isinstance(exc, serializers.ValidationError):
        if isinstance(exc.detail, list):
            message = exc.detail[0]
        elif isinstance(exc.detail, dict):
            for key, value in exc.detail.items():
                if key != "error":
                    message += key + "错误:"
                message += value[0]
        else:
            message = list(exc.detail)[0]
    elif isinstance(exc, AuthenticationFailed) or isinstance(exc, ExpiredSignatureError):
        message = str(exc)
        errcode = 460
    elif isinstance(exc, MultiValueDictKeyError):
        message = '缺少参数:' + str(exc)
    else:
        traceback.print_exc()
        message = str(exc)

    return response_error(message, errcode=errcode)
